//
//  SearchIPsViewController.swift
//  elarc01
//
//  Created by elarc on 16/3/21.
//  Copyright © 2016年 elarc. All rights reserved.
//

import Foundation
import TransitionTreasury

enum SearchStatus{
    case HotSearch
    case SuggestSearch
    case ResultSearch
}

class SearchIPsViewController:UIViewController {
    
    var searchStatus:SearchStatus?
    
    internal  var searchBgView:UIView!
    internal  var canCelBtn:UIButton!
    private let contentScrollView = UIScrollView(frame: ScreenBounds)
    internal let searchBar = UISearchBar()
    private var hotSearchView:SearchView?
    private var historySearchView:SearchView?
    private let cleanHistoryButton:UIButton = UIButton()
    private var searchTableView:UITableView?
    private var ips:[IPs]?   //jsonModel
//    private var searchEmpty:UIView  搜索空页面
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        buildContentScrollView()
        buildSearchBar()
        buildCleanHistorySearchButton()
        
        loadHotSearchButtonData()
        loadHistorySearchButtonData()
        
        bulidSearchTableView()

    }
    
    func buildContentScrollView(){
        contentScrollView.alwaysBounceVertical = true
        contentScrollView.delegate = self
        view.addSubview(contentScrollView)
    }
    
    func buildSearchBar(){
        (navigationController as! BaseNavigationController).backBtn.frame = CGRectMake(0, 0, ScreenWidth, 40)
        
        let tempView = UIView(frame: CGRectMake(0, 0, ScreenWidth * 0.8, 30))
        tempView.backgroundColor = UIColor.whiteColor()
        tempView.layer.cornerRadius = 6
        tempView.layer.masksToBounds = true
        tempView.layer.borderColor = UIColor(red: 100/255, green: 100/255, blue: 100/255, alpha: 1).CGColor
        tempView.layer.borderWidth = 0.2
        let image = UIImage.createImageFromView(tempView)
        
        searchBar.frame = CGRectMake(20, 0, ScreenWidth * 0.8, 30)
        searchBar.placeholder = "搜索作品/版权方/简介/类别/标签等"
        searchBar.barTintColor = UIColor.whiteColor()
        searchBar.keyboardType = UIKeyboardType.Default
        searchBar.setSearchFieldBackgroundImage(image, forState: .Normal)
        searchBar.delegate = self
        
        canCelBtn = UIButton(frame: CGRectMake(ScreenWidth - 40, 5, 30, 18))
        canCelBtn.setTitle("取消", forState: .Normal)
        canCelBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
        canCelBtn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        canCelBtn.addTarget(self, action: #selector(SearchIPsViewController.canCelButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        searchBgView = UIView(frame: CGRectMake(0, 0, ScreenWidth, 44))
        searchBgView.backgroundColor = UIColor.greenColor()
        searchBgView.addSubview(canCelBtn)
        searchBgView.addSubview(searchBar)
 
        navigationItem.titleView = searchBgView
        
        let navVC = navigationController as! BaseNavigationController
        let leftBtn = navigationItem.leftBarButtonItem?.customView as? UIButton
        leftBtn?.addTarget(self, action: #selector(SearchIPsViewController.leftButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        navVC.isAnimation = false
    }
    
    func canCelButtonClick() {
        dismissViewControllerAnimated(true) { () -> Void in
        }
    }
    
    func leftButtonClick() {
        searchBar.endEditing(false)
    }
    
    /// MARK: - 创建清空历史按钮
    func buildCleanHistorySearchButton(){
        cleanHistoryButton.setTitle("清 空 历 史", forState: UIControlState.Normal)
        cleanHistoryButton.setTitleColor(UIColor.colorWithCustom(163, g: 163, b: 163,alpha: 1), forState: UIControlState.Normal)
        cleanHistoryButton.titleLabel?.font = UIFont.systemFontOfSize(14)
        cleanHistoryButton.backgroundColor = view.backgroundColor
        cleanHistoryButton.layer.cornerRadius = 5
        cleanHistoryButton.layer.borderColor = UIColor.colorWithCustom(200, g: 200, b: 200,alpha: 1).CGColor
        cleanHistoryButton.layer.borderWidth = 0.5
        cleanHistoryButton.hidden = true
        cleanHistoryButton.addTarget(self, action: "cleanSearchHistorySearch", forControlEvents: UIControlEvents.TouchUpInside)
        contentScrollView.addSubview(cleanHistoryButton)
    }
    
    /// MARK: - cleanSearchHistorySearch
    func cleanSearchHistorySearch(){
        var  historySearch = NSUserDefaults.standardUserDefaults().objectForKey(CWSearchViewControllerHistorySearchArray) as? [String]
        historySearch?.removeAll()
        NSUserDefaults.standardUserDefaults().setObject(historySearch, forKey: CWSearchViewControllerHistorySearchArray)
        loadHistorySearchButtonData()
        updateCleanHistoryButton(true)
    }
    
    func updateCleanHistoryButton(hiden:Bool){
        if historySearchView != nil {
            cleanHistoryButton.frame = CGRectMake(0.1 * ScreenWidth, CGRectGetMaxY(historySearchView!.frame) + 20, ScreenWidth * 0.8, 40)
        }
              cleanHistoryButton.hidden = hiden
    }
    
    /// MARK: - 创建搜索联想词tableview
    func bulidSearchTableView(){
        searchTableView = UITableView(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64))
        searchTableView!.delegate = self
        searchTableView!.dataSource = self
        searchTableView!.hidden = true
        view .addSubview(searchTableView!)
    }
    
    /// MARK: - 加载热门搜索 需加网络请求
    func loadHotSearchButtonData(){
        searchStatus = SearchStatus.HotSearch
        var array:[String]?
        var historySearch = NSUserDefaults.standardUserDefaults().objectForKey(CWSearchViewControllerHistorySearchArray) as? [String]
        if historySearch == nil {
            historySearch = [String]()
            NSUserDefaults.standardUserDefaults().setObject(historySearch, forKey: CWSearchViewControllerHistorySearchArray)
        }
        weak var tempSelf = self
        let pathStr = NSBundle.mainBundle().pathForResource("SearchIP", ofType: nil)
        let data = NSData(contentsOfFile: pathStr!)
        if data != nil {
            let dict:NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)) as!NSDictionary
            array = (dict.objectForKey("data")! as! NSDictionary).objectForKey("hotquery") as? [String]
            if array?.count > 0 {
                hotSearchView = SearchView(frame: CGRectMake(10, 20, ScreenWidth - 20, 100), searchTitleText: "热门搜索", searchButtonTitleTexts: array!) { (sender) -> () in
                    let str = sender.titleForState(UIControlState.Normal)
                    tempSelf!.writeHistorySearchToUserDefault(str!)
                    tempSelf!.searchBar.text = sender.titleForState(UIControlState.Normal)
                    tempSelf!.loadIPsWithKeyword(sender.titleForState(UIControlState.Normal)!)
                }
                hotSearchView!.frame.size.height = hotSearchView!.searchHeight
                contentScrollView.addSubview(hotSearchView!)
            }
        }
    }
    
    ///  MARK: - 加载联想词结果页 需加网络请求
    ///
    ///  - parameter keyWord: 关键字
    func loadSuggestArrayWithKeyword(keyWord:String?){
        searchStatus = SearchStatus.SuggestSearch
        if keyWord == nil || keyWord?.characters.count == 0{
            return
        }
        
        print("正在全力加载中...")
        
        weak var tempSelf = self
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC)))
        dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
            SearchIPs.loadSearchData{ (data, error) -> Void in
                if data?.data?.count > 0{
                    tempSelf?.ips = data!.data!
                    tempSelf?.searchTableView?.hidden = false
                    tempSelf?.searchTableView?.reloadData()
                    tempSelf?.searchTableView?.setContentOffset(CGPointMake(0, -80), animated: false)
                    print("加载结束")
                }
            }
        }
    }

    
    ///  MARK: - 加载结果页 需加网络请求
    ///
    ///  - parameter keyWord: 关键字
    func loadIPsWithKeyword(keyWord:String?){
        searchStatus = SearchStatus.ResultSearch
        if keyWord == nil || keyWord?.characters.count == 0{
            return
        }
        
        print("正在全力加载中...")
        
        weak var tempSelf = self
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC)))
        dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
            SearchIPs.loadSearchData{ (data, error) -> Void in
                if data?.data?.count > 0{
                    tempSelf?.ips = data!.data!
                    tempSelf?.searchTableView?.hidden = false
                    tempSelf?.searchTableView?.reloadData()
                    tempSelf?.searchTableView?.setContentOffset(CGPointMake(0, -80), animated: false)
                    print("加载结束")
                }
            }
        }
    }
    
    /// MARK: - 添加搜索记录
    func writeHistorySearchToUserDefault(str: String){
        var historySearch = NSUserDefaults.standardUserDefaults().objectForKey(CWSearchViewControllerHistorySearchArray) as? [String]
        for text in historySearch! {
            if text == str {
                return
            }
        }
        historySearch!.append(str)
        NSUserDefaults.standardUserDefaults().setObject(historySearch, forKey: CWSearchViewControllerHistorySearchArray)
        loadHistorySearchButtonData()
    }
    
    /// MARK: - 加载历史搜索记录
    func loadHistorySearchButtonData(){
        if historySearchView != nil {
            historySearchView?.removeFromSuperview()
            historySearchView = nil
        }
        weak var tempSelf = self
        let array = NSUserDefaults.standardUserDefaults().objectForKey(CWSearchViewControllerHistorySearchArray) as? [String]
        if array?.count > 0 {
            historySearchView = SearchView(frame: CGRectMake(10, CGRectGetMaxY(hotSearchView!.frame) + 20, ScreenWidth - 20, 0), searchTitleText: "历史记录", searchButtonTitleTexts: array!, searchButtonClickCallback: { (sender) -> () in
            tempSelf!.searchBar.text = sender.titleForState(UIControlState.Normal)
            tempSelf!.loadIPsWithKeyword(sender.titleForState(UIControlState.Normal)!)
        })
            historySearchView!.frame.size.height = historySearchView!.searchHeight
            contentScrollView.addSubview(historySearchView!)
            updateCleanHistoryButton(false)
      }
    }
}
    extension SearchIPsViewController:UISearchBarDelegate,UIScrollViewDelegate{
        func searchBarSearchButtonClicked(searchBar:UISearchBar){
            if searchBar.text?.characters.count > 0 {
                writeHistorySearchToUserDefault(searchBar.text!)
                loadIPsWithKeyword(searchBar.text!)
            }
        }
        
        func scrollViewDidScroll(scrollView: UIScrollView) {
            searchBar.endEditing(false)
        }
        
        func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
            if searchText.characters.count == 0 {
                searchTableView?.hidden = true
            }else{
                contentScrollView.hidden = true
                searchTableView?.hidden = false
                loadSuggestArrayWithKeyword(searchBar.text!)
            }
            
        }
}

    extension SearchIPsViewController:UITableViewDelegate,UITableViewDataSource{
        
        func numberOfSectionsInTableView(tableView: UITableView) -> Int {
             return 1
        }
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
             return ips?.count ?? 0
        }
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
             let searchCellId = "SearchIpCell"
             var cell = tableView.dequeueReusableCellWithIdentifier(searchCellId)
             if cell == nil {
               cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: searchCellId)
             }
            if searchStatus == SearchStatus.SuggestSearch {
                cell?.textLabel?.text = "联想热词语"
            }
             return cell!
        }
        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
            print("搜索")
        }
        
}
